package com.common.util;

import java.security.MessageDigest;

/**
 * @author: zhaojd1604@gmail.com
 * @date: 2019/1/2
 * @description: MD5工具类
 * @since: V0.0.1
 */
public class MD5Util {

    private static final String CHARSET = "UTF-8";

    /**
     * @param content 需要加密的字符串
     * @return 32位16进制字符串,如需要16位,则subtring(8, 25)
     */
    public final static String md5(String content) {
        // 用于加密的字符,常用A ~ F即可
        char[] md5String = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z'};
        try {
            byte[] btInput = content.getBytes(CHARSET);
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            // 密文转换成十六进制的字符串
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = md5String[byte0 >>> 4 & 0xf];
                str[k++] = md5String[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(md5("abc"));
    }
}